import 'package:flutter/material.dart';
import 'package:flutter_hex_color/flutter_hex_color.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:get/get.dart';
import 'package:signage/app/data/models/member_group_model.dart';
import 'package:signage/app/data/models/member_info_item_model.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/custom_appbar.dart';
import 'package:signage/widgets/edit_dialog.dart';

import '../controllers/choose_list_controller.dart';
import 'add_member_dialog.dart';

class ChooseListView extends GetView<ChooseListController> {
  const ChooseListView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(ChooseListController());
    return Obx(() {
      return Scaffold(
        backgroundColor: HexColor('#F3F4F6'),
        appBar: CustomAppBar(
          backgroundColor: Colors.white,
          title: logic.isSelecting.value 
              ? AppLocalizations.of(context)!.translate('choose_list')
              : AppLocalizations.of(context)!.translate('selected_members'),
          showBackButton: true,
          rightButtons: logic.isSelecting.value
              ? [
                  GestureDetector(
                      onTap: () => controller.showImportDialog(context),
                      child: Row(
                        children: [
                          Image.asset(
                            'assets/images/Frame@2x (10).png',
                            width: 19.w,
                            height: 19.w,
                            fit: BoxFit.contain,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            AppLocalizations.of(context)!.translate('import_list'),
                            style: TextStyle(
                                fontSize: 14.w,
                                fontWeight: FontWeight.w500,
                                color: HexColor('#333333')),
                          ),
                        ],
                      )),
                  10.w.horizontalSpace,
                ]
              : null,
        ),
        body: Container(
          padding: EdgeInsets.only(left: 0.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 分组列表部分
              Obx(
                () => !logic.isSelecting.value
                    ? SizedBox()
                    : Container(
                        color: Colors.white,
                        height: 60.w,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              child: ListView.builder(
                                shrinkWrap: true,
                                scrollDirection: Axis.horizontal,
                                physics: AlwaysScrollableScrollPhysics(),
                                itemCount: logic.groupList.length,
                                itemBuilder: (_, index) => _buildSegCell(
                                    logic.getIndexGroup(index), index),
                              ),
                            ),
                            TextButton(
                              onPressed: () => controller.addNewGroup(),
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 13.5.w, vertical: 4.w),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(4.w),
                                  color: HexColor('#FCCF01'),
                                ),
                                child: Row(
                                  children: [
                                    Image.asset(
                                      'assets/images/choose_list_add_group@2x.png',
                                      width: 16.w,
                                      height: 16.w,
                                      fit: BoxFit.contain,
                                    ),
                                    SizedBox(
                                      width: 5.w,
                                    ),
                                    Text(
                                      AppLocalizations.of(context)!.translate('add_group'),
                                      style: TextStyle(
                                          fontSize: 14.w,
                                          fontWeight: FontWeight.normal,
                                          color: HexColor('#333333')),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
              ),
              Container(
                color: HexColor('#F9F9F9'),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Text(
                          logic.currentGroup.value?.groupName ?? "暂无",
                          style: TextStyle(
                              fontSize: 16.w,
                              fontWeight: FontWeight.w500,
                              color: HexColor('#333333')),
                        ),
                        SizedBox(
                          width: 10.w,
                        ),
                        GestureDetector(
                            onTap: () => logic.isSelecting.value
                                ? _showEditGroupNameDialog(context)
                                : null,
                            child: Image.asset(
                              'assets/images/choose_list_edit@2x.png',
                              width: 16.w,
                              height: 16.w,
                              fit: BoxFit.contain,
                            )),
                        SizedBox(
                          width: 10.w,
                        ),
                        GestureDetector(
                            onTap: () => logic.touchGroupSegDelete(
                                logic.currentGroupIndex.value),
                            child: Image.asset(
                              'assets/images/choose_list_delete@2x.png',
                              width: 16.w,
                              height: 16.w,
                              fit: BoxFit.contain,
                            )),
                      ],
                    ),
                    GestureDetector(
                      onTap: () => controller.showAddMemberDialog(context),
                      child: Container(
                        height: 26.w,
                        decoration: BoxDecoration(
                        color: HexColor('#FCCF01'),
                        borderRadius: BorderRadius.circular(4.r),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          5.horizontalSpace,
                          Icon(
                            Icons.add,
                            size: 16.w,
                            color: HexColor('#333333'),
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            AppLocalizations.of(context)!.translate('member'),
                            style: TextStyle(
                              fontSize: 14.w,
                              color: HexColor('#333333'),
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                          5.horizontalSpace,
                        ],
                      ),
                      )),
                  ],
                ),
              ),
              // 成员列表部分
              Expanded(
                child: Container(
                  padding:
                      EdgeInsets.only(left: 16.w, right: 16.w, bottom: 16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: ListView.builder(
                          shrinkWrap: false,
                          physics: AlwaysScrollableScrollPhysics(),
                          itemCount:
                              logic.currentGroup.value?.memberList?.length ?? 0,
                          itemBuilder: (_, index) => _buildMemberCell(
                              logic.currentGroup.value?.memberList?[index],
                              index),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        bottomNavigationBar: logic.isSelecting.value
            ? Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.w),
                color: Colors.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Row(
                      children: [
                        GestureDetector(
                          onTap: () {
                            if (controller.currentGroup.value?.memberList !=
                                null) {
                              bool allSelected = controller
                                  .currentGroup.value!.memberList!
                                  .every((member) => member.choose == true);

                              for (var member in controller
                                  .currentGroup.value!.memberList!) {
                                member.choose = !allSelected;
                              }
                              controller.currentGroup.refresh();
                            }
                          },
                          child: Container(
                            margin: EdgeInsets.only(right: 0),
                            width: 18,
                            height: 18,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: controller.currentGroup.value?.memberList
                                              ?.every((member) =>
                                                  member.choose == true) ==
                                          false ||
                                      controller.currentGroup.value?.memberList
                                              ?.isEmpty ==
                                          true
                                  ? Border.all(
                                      color: Colors.grey,
                                      width: 1,
                                    )
                                  : null,
                              color: controller.currentGroup.value?.memberList
                                              ?.every((member) =>
                                                  member.choose == true) ==
                                          true &&
                                      controller.currentGroup.value?.memberList
                                              ?.isEmpty ==
                                          false
                                  ? HexColor('#FCCF01')
                                  : Colors.white,
                            ),
                            child: (controller.currentGroup.value?.memberList
                                            ?.every((member) =>
                                                member.choose == true) ==
                                        true &&
                                    controller.currentGroup.value?.memberList
                                            ?.isEmpty ==
                                        false)
                                ? Icon(
                                    Icons.check,
                                    size: 16,
                                    color: Colors.black,
                                  )
                                : null,
                          ),
                        ),
                        10.horizontalSpace,
                        GestureDetector(
                          onTap: () {
                            if (controller.currentGroup.value?.memberList !=
                                null) {
                              bool allSelected = controller
                                  .currentGroup.value!.memberList!
                                  .every((member) => member.choose == true);

                              for (var member in controller
                                  .currentGroup.value!.memberList!) {
                                member.choose = !allSelected;
                              }
                              controller.currentGroup.refresh();
                            }
                          },
                          child: Text(
                            AppLocalizations.of(context)!.translate('select_all'),
                            style: TextStyle(
                              fontSize: 16.w,
                              fontWeight: FontWeight.w400,
                              letterSpacing: 0,
                              color: Color.fromARGB(255, 51, 51, 51),
                            ),
                          ),
                        ),
                      ],
                    ),
                    if (controller.currentGroup.value?.memberList
                                ?.every((member) => member.choose == true) ==
                            true &&
                        controller.currentGroup.value?.memberList?.isEmpty ==
                            false)
                      GestureDetector(
                        onTap: () => controller.clearMemberList(),
                        behavior: HitTestBehavior.translucent,
                        child: Row(
                          children: [
                            20.horizontalSpace,
                            Image.asset(
                              'assets/images/Ve2ctor@2x.png',
                              width: 16.w,
                              height: 16.w,
                              fit: BoxFit.contain,
                            ),
                            8.w.horizontalSpace,
                            Text(
                              AppLocalizations.of(context)!.translate('clear_list'),
                              style: TextStyle(
                                fontSize: 16.w,
                                fontWeight: FontWeight.w400,
                                letterSpacing: 0,
                                color: Color.fromARGB(255, 51, 51, 51),
                              ),
                            ),
                          ],
                        ),
                      ),
                    20.horizontalSpace,
                    Expanded(
                      child: Container(
                        height: 40.w,
                        child: TextButton(
                          onPressed: () => controller.confirmSelection(),
                          style: TextButton.styleFrom(
                            backgroundColor: HexColor('#FCCF01'),
                          ),
                          child: Text(
                            AppLocalizations.of(context)!.translate('confirm'),
                            style: TextStyle(color: HexColor('#333333')),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )
            : null,
      );
    });
  }

  Widget _buildSegCell(MemberGroup? info, index) => Container(
        padding: EdgeInsets.only(right: 15.w),
        child: Stack(
          alignment: Alignment.topRight,
          children: [
            GestureDetector(
              onTap: () {
                controller.touchGroupSeg(index);
              },
              child: Column(
                children: [
                  ClipRRect(
                    child: Container(
                      // color: Color(0xFFDEF0E8),
                      padding: EdgeInsets.only(
                          left: 10.w, right: 10.w, top: 10.w, bottom: 5.w),
                      child: Text(
                        info?.groupName ?? AppLocalizations.of(Get.context!)!.translate('no_group_name'),
                        style: TextStyle(
                            fontSize: 16.w,
                            fontWeight:
                                controller.currentGroupIndex.value == index
                                    ? FontWeight.w500
                                    : FontWeight.w400,
                            color: controller.currentGroupIndex.value == index
                                ? HexColor('#333333')
                                : HexColor('#666666')),
                      ),
                    ),
                  ),
                  if (controller.currentGroupIndex.value == index)
                    Image.asset(
                      'assets/images/yellow_slider.png',
                      width: 13.w,
                      height: 5.w,
                      fit: BoxFit.contain,
                    ),
                ],
              ),
            ),

            // IconButton(
            //     style: TextButton.styleFrom(
            //         minimumSize: Size.zero,
            //         padding: EdgeInsets.zero,
            //         tapTargetSize:
            //         MaterialTapTargetSize.shrinkWrap),
            //     onPressed: () => {
            //       controller.touchGroupSegDelete(index)
            //     },
            //     icon: Icon(Icons.remove_circle),
            //     iconSize: 25.w,
            //     color: Colors.red),
          ],
        ),
      );

  Widget _buildMemberCell(MemberItem? info, index) => Column(
        children: [
          16.verticalSpace,
          Row(
            children: [
              Image.asset(
                'assets/images/Group 1321318618@2x.png',
                width: 17.w,
                height: 18.w,
                fit: BoxFit.contain,
              ),
              SizedBox(
                width: 10.w,
              ),
              Text(
                AppLocalizations.of(Get.context!)!.translate('member_number', params: {'index': (index + 1).toString()}),
              ),
              Expanded(child: SizedBox()),
              GestureDetector(
                  onTap: () async {
                    if (info != null) {
                      controller.showEditMemberDialog(index, info);
                    }
                  },
                  child: Image.asset(
                    'assets/images/Frame@2x (12).png',
                    width: 16.w,
                    height: 16.w,
                    fit: BoxFit.contain,
                  )),
              16.horizontalSpace,
              GestureDetector(
                  onTap: () async {
                    if (info != null) {
                      controller.copyMember(info);
                    }
                  },
                  child: Image.asset(
                    'assets/images/Frame@2x (13).png',
                    width: 16.w,
                    height: 16.w,
                    fit: BoxFit.contain,
                  )),
              16.horizontalSpace,
              GestureDetector(
                  onTap: () async {
                    if (info != null) {
                      await controller.showDeleteConfirmDialog(info);
                    }
                  },
                  child: Image.asset(
                    'assets/images/choose_list_delete@2x.png',
                    width: 16.w,
                    height: 16.w,
                    fit: BoxFit.contain,
                  )),
            ],
          ),
          SizedBox(
            height: 10.w,
          ),
          Row(
            children: [
              // 隐藏选择框
              if (controller.isSelecting.value)
                GestureDetector(
                  onTap: () {
                    if (info != null) {
                      info.choose = !(info.choose ?? false);
                      controller.currentGroup.refresh();
                    }
                  },
                  child: Container(
                    width: 18,
                    height: 18,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: info?.choose == false
                          ? Border.all(
                              color: Colors.grey,
                              width: 1,
                            )
                          : null,
                      color: (info?.choose ?? false)
                          ? HexColor('#FCCF01')
                          : Colors.white,
                    ),
                    child: (info?.choose ?? false)
                        ? const Icon(
                            Icons.check,
                            size: 14,
                            color: Colors.black,
                          )
                        : null,
                  ),
                ),
              SizedBox(
                width: 10.w,
              ),
              Expanded(
                  child: ClipRRect(
                borderRadius: BorderRadius.circular(12.r),
                child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.all(15.w),
                  width: 315.w,
                  child: ListView.builder(
                    shrinkWrap: true,
                    scrollDirection: Axis.vertical,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: info?.memberInfoList?.length ?? 0,
                    itemBuilder: (_, index) =>
                        _buildMemberInfoCell(info?.memberInfoList?[index]),
                  ),
                ),
              )),
            ],
          ),
        ],
      );
  Widget _buildMemberInfoCell(MemberInfoItem? info) => GestureDetector(
        onTap: () {
          // logic.tapImage(index);
        },
        child: Row(
          children: [
            Expanded(
                child: Text(
              info?.keyName ?? "暂无",
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                letterSpacing: 0,
                color: Color.fromARGB(255, 51, 51, 51),
              ),
            )),
            Text(info?.value ?? "暂无",
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                  letterSpacing: 0,
                  color: Color.fromARGB(255, 51, 51, 51),
                ))
          ],
        ).paddingSymmetric(vertical: 8.w),
      );

  void _showEditGroupNameDialog(BuildContext context) {
    final TextEditingController textController =
        TextEditingController(text: controller.currentGroup.value?.groupName);

    Get.dialog(
      EditDialog(
        title: AppLocalizations.of(context)!.translate('edit_group_name'),
        hintText: AppLocalizations.of(context)!.translate('enter_new_group_name'),
        controller: textController,
        onConfirm: () {
          Get.back();
          if (controller.currentGroup.value != null) {
            controller.currentGroup.update((group) {
              group?.groupName = textController.text;
            });
          }
        },
      ),
    );
  }
}
